<?php
/**
 * bs多规格sku商城系统
 * ============================================================================
 * 版权所有 2024-2099 wltx666.com，并保留所有权利。
 * 网站地址: https://wltx666.com
 * ============================================================================
 * Author: 草上飞
 * Email: wltx@alipay168.cn
 * QQ: 2719875001
 * Date: 2025/06/02
 * 描述: api_xxx 代表前端接口,其它代表后端接口
 */

namespace app\result\auto;

use app\model\admin\Admin;
use app\model\auto\GoodsStockLog;
use app\model\goods\Goods;
use app\model\goods\GoodsSpecPrice;
use app\result\BaseResult;
use app\result\goods\GoodsActionResult;
use think\facade\Db;


class GoodsStockLogResult extends BaseResult
{
    public function __construct()
    {
        parent::__construct();
        $this->model = new GoodsStockLog();
    }

    // 保存数据
    public function save_data($args): array
    {
        $rules = [
            ['type', 'number|in_array:1,2,3', '类型必传|类型错误'],
            ['goods_id', 'empty', '请选择商品'],
            ['remark', 'empty|max:200', '请备注|备注长度不能大于200'],
            ['change_num', 'empty|min:1', '请填写数量|不得小于1'],
        ];
        $check = check_param($args, $rules);
        if ($check['status'] != 0) {
            return self::error_return($check['msg']);
        }
        $goods_id = $args['goods_id'];
        $goodsModel = new Goods();
        $goodsModel->isWithTrashed = true;
        $goods = $goodsModel->data_get(['goods_id' => $args['goods_id']], 'goods_id,store_count,is_sku');
        if (!$goods) {
            return self::error_return('商品不存在');
        }
        if ($goods['is_sku'] && empty($args['spec_id'])) {
            return self::error_return('请选择规格');
        }
        $before_stock = $goods['store_count'];
        if (!empty($args['spec_id'])) {
            $before_stock = (new GoodsSpecPrice())->get_value(['spec_id' => $args['spec_id']], 'store_count');
        }
        if ($args['type'] == 1) {
            $after_stock = $before_stock + $args['change_num'];
        } else {
            $after_stock = $before_stock - $args['change_num'];
        }
        if ($after_stock < 0) {
            return self::error_return('最终库存不能小于0');
        }
        $baseData = [
            'remark' => $args['remark'],
            'admin_id' => $args['admin_id'],
            'spec_id' => intval($args['spec_id']),
            'goods_id' => intval($args['goods_id']),
            'type' => intval($args['type']),
            'change_num' => intval($args['change_num']),
            'before_stock' => intval($before_stock),
            'after_stock' => intval($after_stock),
        ];

        Db::startTrans();
        try {
            $res = $this->model->data_add($baseData);
            if (!$res) {
                throw new \Exception('记录失败');
            }
            if ($baseData['spec_id']) {
                $res = (new GoodsSpecPrice())->data_update(['spec_id' => $args['spec_id']], ['store_count' => $after_stock]);
            } else {
                $res = (new Goods())->data_update(['goods_id' => $args['goods_id']], ['store_count' => $after_stock]);
            }
            if (!$res) {
                throw new \Exception('更新商品库存失败');
            }
        } catch (\Exception $e) {
            Db::rollback();
            return self::error_return('保存失败:' . $e->getMessage());
        }
        Db::commit();
        !empty($args['spec_id']) && (new GoodsActionResult())->sync_goods_base($goods_id);
        return $this->success_return('保存成功');
    }

    // 表格列
    public function el_table_column(): array
    {
        return [
            ['prop' => 'id', 'type' => 'text', 'label' => 'id', 'minWidth' => '100', 'align' => 'center',],
            ['prop' => 'goods_name', 'type' => 'text', 'label' => '商品名称', 'minWidth' => '120', 'align' => 'left',],
            ['prop' => 'spec_name', 'type' => 'text', 'label' => '关联规格', 'minWidth' => '120', 'align' => 'left',],
            ['prop' => 'type', 'type' => 'tags', 'label' => '类型', 'minWidth' => '120', 'align' => 'center',
                'tags' => [
                    1 => ['label' => '入库', 'value' => '1', 'type' => 'success'],
                    2 => ['label' => '出库', 'value' => '2',],
                    3 => ['label' => '其它', 'value' => '3',],
                ]],
            ['prop' => 'change_num', 'type' => 'text', 'label' => '数量', 'minWidth' => '120', 'align' => 'center',],
            ['prop' => 'before_stock', 'type' => 'text', 'label' => '操作前数量', 'minWidth' => '120', 'align' => 'center',],
            ['prop' => 'after_stock', 'type' => 'text', 'label' => '操作后数量', 'minWidth' => '120', 'align' => 'center',],
            ['prop' => 'remark', 'type' => 'text', 'label' => '备注', 'minWidth' => '120', 'align' => 'center',],
            ['prop' => 'created_at', 'type' => 'text', 'label' => '生成时间', 'minWidth' => '120', 'align' => 'center',],
            ['prop' => 'admin_name', 'type' => 'text', 'label' => '操作人', 'minWidth' => '120', 'align' => 'center',],
        ];
    }

    //列表搜索字段
    private function _searchField(): array
    {
        return [
            ['name' => 'type', 'label' => '类型', 'type' => 'select', 'placeholder' => '类型',
                'options' => [
                    1 => ['label' => '进库', 'value' => '1',],
                    2 => ['label' => '出库', 'value' => '2',],
                    3 => ['label' => '订单操作', 'value' => '3',],
                ]
            ]
        ];
    }

    // 获取公共条件限制
    private function _where($args = []): array
    {
        $where = [];
        $keyword = trim($args['keyword'] ?? '');
        $status = $args['status'] ?? '';
        $type = $args['type'] ?? '';
        if ($keyword) {
            $where[] = ['remark', 'like', '%' . trim($args['keyword']) . '%'];
        }
        if ($type) {
            $where[] = ['type', '=', $type];
        }

        if ($status) {
            $where[] = ['status', '=', $status];
        }
        return $where;
    }

    public function list($args = []): array
    {
        $page = intval($args['page'] ?? 1);
        $pageSize = intval($args['limit'] ?? 10);
        $sort_by = trim($args['sort_by'] ?? 'id desc');
        $where = $this->_where($args);
        $total = $this->model->data_count($where);
        $data = $this->model->data_list($where, '*', $sort_by, $page, $pageSize)?->toArray();
        if ($data) {
            $modelGoods = new Goods();
            $modelGoods->isWithTrashed = true;
            $modelSpecPrice = new GoodsSpecPrice();
            $goods = $modelGoods->data_list_nopage([['goods_id', 'in', array_unique(array_column($data, 'goods_id'))]], 'goods_id,goods_name,is_sku');
            if ($goods) {
                $goods = array_column($goods, null, 'goods_id');
            }
            $specIds = array_unique(array_column($data, 'spec_id'));
            if ($specIds) {
                $specs = $modelSpecPrice->data_list_nopage([['spec_id', 'in', $specIds]], 'spec_id,spec_name');
                if ($specs) {
                    $specs = array_column($specs, null, 'spec_id');
                }
            }
            $modelAdmin = new Admin();
            $adminIds = array_unique(array_column($data, 'admin_id'));
            $admins = $modelAdmin->data_list_nopage([['admin_id', 'in', $adminIds]], 'admin_id,username');
            if ($admins) {
                $admins = array_column($admins, null, 'admin_id');
            }
            foreach ($data as &$item) {
                $item['goods_name'] = $goods[$item['goods_id']]['goods_name'] ?? '【已删除】';
                $item['spec_name'] = $specs[$item['spec_id']]['spec_name'] ?? '--';
                $item['admin_name'] = $admins[$item['admin_id']]['username'] ?? '【已删除】';
            }
            unset($item);
        }
        return $this->success_return('success', [
            'total' => $total,
            'list' => $data,
            'el_table_column' => $this->el_table_column(),
            'search_fields' => $this->_searchField()
        ]);
    }

    public function query_goods($args): array
    {
        $goods_id = intval($args['goods_id'] ?? 0);
        if (!$goods_id) {
            return $this->error_return('参数错误');
        }
        $modelGoods = new Goods();
        $modelGoods->isWithTrashed = true;
        $data = $modelGoods->data_get(['goods_id' => $goods_id], 'goods_id,goods_name,is_sku,store_count');
        if (!$data) {
            return $this->error_return('商品不存在');
        }
        $data['sku_list'] = [];
        if ($data['is_sku']) {
            $data['sku_list'] = $modelGoods->goods_sku_list($goods_id);
            if ($data['sku_list']) {
                foreach ($data['sku_list'] as &$item) {
                    $item['value'] = $item['spec_id'];
                    $item['label'] = $item['spec_name'] . '(剩余：' . $item['store_count'] . ')';
                }
            }
        }
        return $this->success_return('success', $data);
    }


}
